package euler.p001_050;

import euler.MainEuler;

public class Euler050 extends MainEuler {

    /*
        The prime 41, can be written as the sum of six consecutive primes:
        41 = 2 + 3 + 5 + 7 + 11 + 13

        This is the longest sum of consecutive primes that adds to a prime
        below one-hundred.

        The longest sum of consecutive primes below one-thousand that adds
        to a prime, contains 21 terms, and is equal to 953.

        Which prime, below one-million, can be written as the sum of the
        most consecutive primes?

     */
    public String resolve(int limite) {

        int longestSum = 0;
        int targetPrime = 0;

        for (int i = 2; i <= limite; i++) {
            if (primeHelper.isPrime(i)) {
                int n = i;
                int countPrimes = 0;
                int suma = 0;

                while (suma < limite) {
                    if (longestSum < countPrimes && primeHelper.isPrime(suma)) {
                        longestSum = countPrimes;
                        targetPrime = suma;
                    }

                    suma+=n;
                    countPrimes++;
                    n = nextPrime(n);
                }
            }
        }

        return String.valueOf(targetPrime);
        // 997651
    }

    private static int nextPrime(int n) {
        while(!primeHelper.isPrime(++n)) {}

        return n;
    }

}
